package cn.nuomi.shop.api.filter;

import cn.nuomi.shop.api.vo.BaseRespVO;
import com.alibaba.fastjson.JSON;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;

/**
 * @date: 2021/4/26 15:04
 * @description: 用户登录验证过滤器
 */
public class AuthenticationFilter implements Filter {

    String[] whiteList = {"/login","/register"};


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //获取当前请求地址
        String requestURI = req.getRequestURI();
        StringBuffer requestURL = req.getRequestURL();

        //跳过无需过滤的地址（白名单）
        boolean existWhiteList = Arrays.stream(whiteList)
                .anyMatch(item -> requestURI.contains(item));
        if (existWhiteList){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        //判断用户是否登录
        HttpSession session = req.getSession();

        //session过期
        if (null == session) {
            errorResp(resp,"用户已过期");
            return;
        }

        Object sessionUserObj = session.getAttribute("sessionUser");
        if (null == sessionUserObj){
            errorResp(resp,"用户未登录");
            return;
        }

        //用户登录验证通过
        filterChain.doFilter(servletRequest,servletResponse);
    }

    protected void errorResp(HttpServletResponse resp, String errorMsg) throws IOException {
        BaseRespVO result = new BaseRespVO();
        result.setStatus(BaseRespVO.StatusType.FAILED.getValue());
        result.setMsg(errorMsg);
        //转换为json
        String json = JSON.toJSONString(result);
        //json写入到返回数据区域
        resp.getWriter().write(json);
    }
}
